package com.vsclouds.mp.util;

import org.springframework.http.HttpStatus;

import javax.servlet.http.HttpServletResponse;

import com.vsclouds.mp.util.ResultCode;

/**
 * Created with Software Dept.
 * <p> {@code ResponseDataFactory}
 * response 处理
 *
 * @author : tianbaolei
 * @date : 2020-06-17 16:28
 * Description:
 */
public class ResponseHandler {

    public static final String RESULT_CODE = "resultCode";

    /**
     * 设置 HttpServletResponse 结果码和请求status
     */
    public static HttpServletResponse handle(HttpServletResponse response, HttpStatus status) {
        switch (status) {
            case OK:
                return handle(response, status, ResultCode.R_OPERATION_SUCCESS);
            case BAD_REQUEST:
            case FORBIDDEN:
                return handle(response, status, ResultCode.R_BAD_REQUEST);
            case UNSUPPORTED_MEDIA_TYPE:
                return handle(response, status, ResultCode.R_UNSUPPORTED_MEDIA_TYPE);
            case NOT_FOUND:
                return handle(response, status, ResultCode.R_NOT_FOUND);
            case INTERNAL_SERVER_ERROR:
                return handle(response, status, ResultCode.R_RUNTIME_EXCEPTION);
            default:
                return handle(response, status, ResultCode.R_BAD_REQUEST);
        }
    }

    public static HttpServletResponse handle(HttpServletResponse response, ResultCode resultCode) {
        switch (resultCode) {
            case R_OPERATION_SUCCESS:
                // 200
                return handle(response, HttpStatus.OK, resultCode);
            case R_BAD_REQUEST:
                return handle(response, HttpStatus.BAD_REQUEST, resultCode);
            case R_UNSUPPORTED_MEDIA_TYPE:
                return handle(response, HttpStatus.UNSUPPORTED_MEDIA_TYPE, resultCode);
            case R_NOT_FOUND:
                return handle(response, HttpStatus.NOT_FOUND, ResultCode.R_NOT_FOUND);
            case R_RUNTIME_EXCEPTION:
                return handle(response, HttpStatus.INTERNAL_SERVER_ERROR, ResultCode.R_RUNTIME_EXCEPTION);
            default:
                return handle(response, HttpStatus.BAD_REQUEST, ResultCode.R_BAD_REQUEST);
        }
    }

    /**
     * 设置 HttpServletResponse 结果码和请求status
     */
    public static HttpServletResponse handle(HttpServletResponse response, HttpStatus status, ResultCode resultCode) {
        response.setStatus(status.value());
        response.setHeader(RESULT_CODE, resultCode.toString());
        return response;
    }
}
